package com.yunchang.springboot.scheduled.finance;

import com.yunchang.springboot.mapper.finance.FinanceAccountsSettlementMapper;
import com.yunchang.springboot.mapper.finance.FinanceAccountsSettlementTableColumnsMapper;
import com.yunchang.springboot.models.DO.finance.FinanceAccountsSettlement;
import com.yunchang.springboot.models.DO.finance.FinanceAccountsSettlementTableColumns;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class FinanceAccountsSettlementSchedule {
    @Resource
    FinanceAccountsSettlementMapper financeAccountsSettlementMapper;
    @Resource
    FinanceAccountsSettlementTableColumnsMapper financeAccountsSettlementTableColumnsMapper;

    //@Scheduled(cron = "")
    @Transactional
    public void confirmAccountSettlement(String period) {
        LocalDateTime nowDate = LocalDateTime.now();
        LocalDateTime preMonthDate = nowDate.minusMonths(1);
        Integer year = preMonthDate.getYear();
        Integer month = preMonthDate.getMonthValue();
        //String period = year + "-" + month;
        //先去获得上个月是否有结账标记
        FinanceAccountsSettlement financeAccountsSettlement = financeAccountsSettlementMapper.selectDataByPeriod(period);
        FinanceAccountsSettlement newFinanceAccountsSettlement;
        if (financeAccountsSettlement == null){
            newFinanceAccountsSettlement = new FinanceAccountsSettlement();
            newFinanceAccountsSettlement.setPeriod(period);
            newFinanceAccountsSettlement.setStatus(0);
        }else {
            newFinanceAccountsSettlement = financeAccountsSettlement;
        }
        Integer financeStatus = 1;
        List<FinanceAccountsSettlementTableColumns> allData = financeAccountsSettlementTableColumnsMapper.getAllData();
        OUT:for (FinanceAccountsSettlementTableColumns accountsSettlementTableColumns : allData) {
            List<Integer> settlementStatusFromLastMonth = financeAccountsSettlementMapper.getSettlementStatusFromLastMonth(accountsSettlementTableColumns, year + "" + month);
            for (Integer status : settlementStatusFromLastMonth){
                if (status != 2){
                    financeStatus = 0;
                    break OUT;
                }
            }
        }
        newFinanceAccountsSettlement.setStatus(financeStatus);
        financeAccountsSettlementMapper.replaceData(newFinanceAccountsSettlement);
    }

}
